/*
 * 创建日期 2009-11-27
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.db;

import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import  org.fantasy.common.db.bean.ColumnBean;
import  org.fantasy.common.db.util.SqlUtil;
import  org.fantasy.common.exception.DBException;

/**
 * 抽象查询
 * 
 * @author: 王文成
 * @version: 1.0
 * @since 2009-11-27
 */
public abstract class AbstractQuery extends DataSourceSupport implements Query {

	private static Log log = LogFactory.getLog(AbstractQuery.class);

	protected String sql;

	protected List<Object> values;

	protected Map<Object, Object> paramMap = new HashMap<Object, Object>();

	protected int pageStart;

	protected int pageSize;

	protected String countType;

	public Query setParamMap(Map<String, Object> paramMap) {
		this.paramMap.putAll(paramMap);
		return this;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public void reset() {
		this.pageStart = 0;
		this.pageSize = 0;
	}

	public Query setCountType(String countType) {
		this.countType = countType;
		return this;
	}

	public Query setPage(int pageStart, int pageSize) {
		this.pageStart = pageStart;
		this.pageSize = pageSize;
		return this;
	}

	/**
	 * 初始化SQL
	 */
	protected String prepare(String sql) {
		List<String> params = SqlUtil.getParameterList(sql);
		List<Object> paramValues = new ArrayList<Object>();
		if (!paramMap.isEmpty()) {
			for (String param : params) {
				paramValues.add(paramMap.get(param));
				sql = StringUtils.replaceOnce(sql, ":" + param, "?");
			}
		}
		this.values = paramValues;
		return sql;
	}

	/**
	 * 是否分页
	 * 
	 * @return
	 */
	public boolean isPaged() {
		return this.pageStart > 0 && this.pageSize > 0;
	}

	public Query setParam(String name, Object value) {
		paramMap.put(name, value);
		return this;
	}

	@Override
	public List<ColumnBean> getColumns() throws DBException {
		return new ArrayList<ColumnBean>(0);
	}
}
